<template>
  <view class="container">
   
    <view v-if="gameStarted && !paused" class="game-board" :style="gridStyle">
      <view v-for="(tile, index) in tiles" :key="index" class="tile" @click="handleTileClick(index)">
        <view :class="['tile-inner', { revealed: tile.isRevealed }]">
          <view class="tile-front"></view>
          <view class="tile-back">{{ tile.content }}</view>
        </view>
      </view>
    </view>
	
    <view v-if="gameStarted" class="score-board">分数: {{ score }}</view>
    <view v-if="gameStarted" class="level-board">关卡: {{ currentLevel }}</view>
	
	<view class="games-box">
		<button class="u-button" v-if="gameStarted && !paused" @click="pauseGame" >暂停游戏</button>
		<button class="u-button" v-if="paused" @click="resumeGame" >继续游戏</button>
		<button class="u-button" v-if="!gameStarted" @click="startGame" >开始游戏</button>
		<button class="u-button" v-if="gameStarted" @click="endGame" class="end-button">结束游戏</button>
	</view>
	<u-read-more :toggle="true" showHeight="100">
	    <rich-text :nodes="content"></rich-text>
	</u-read-more>
  </view>
</template>

<script>
export default {
  data() {
    return {
      gridSize: 16,
      tiles: [],
      gameStarted: false,
      paused: false,
      matchedTiles: [],
      score: 0,
      currentLevel: 1,
      totalLevels: 5,
      gridColumns: 4,
	  content:`这款微信小程序记忆游戏的规则如下：
1.游戏目标：玩家需要找出所有配对的方块。

2.开始游戏：游戏开始时，玩家点击“开始游戏”按钮，游戏将初始化一定数量的方块（或称作卡片）并布置在网格中。每个方块有两面，一面是统一的背景色或图案（隐藏面），另一面是唯一的颜色或图案（内容面）。

3.关卡设置：游戏包含多个关卡，每个关卡的方块数量会逐渐增加，难度随之提高。玩家在完成一个关卡后，会自动进入下一个关卡。

4.翻转方块：玩家点击任意一个方块，该方块会翻转，展示其内容面。

5.寻找配对：玩家需要记住每个翻转方块的内容和位置，尝试找出内容相同的一对方块。

6.匹配成功：当玩家找到一对内容相同的方块时，这对方块会保持翻转状态，表示成功匹配。

7.计分机制：每成功匹配一对方块，玩家获得一定的分数。

8.暂停与继续：玩家可以在游戏过程中随时暂停游戏，并在稍后继续从暂停时的状态开始游戏。

9.游戏结束条件：当所有方块都成功匹配后，游戏结束。如果玩家完成了所有设置的关卡，则获得最终胜利。

10.游戏状态保存：玩家的游戏进度会被保存，这意味着玩家可以在退出游戏后，再次进入时从上次离开的关卡继续游戏。`
    };
  },
  computed: {
    gridStyle() {
      return {
        'grid-template-columns': `repeat(${this.gridColumns}, 1fr)`
      };
    }
  },
  onShow() {
    this.loadGame();
  },
  methods: {
    loadGame() {
      let savedGame = uni.getStorageSync('savedGame');
      if (savedGame) {
        this.gridSize = savedGame.gridSize;
        this.tiles = savedGame.tiles;
        this.gameStarted = savedGame.gameStarted;
        this.paused = savedGame.paused;
        this.matchedTiles = savedGame.matchedTiles;
        this.score = savedGame.score;
        this.currentLevel = savedGame.currentLevel;
        this.totalLevels = savedGame.totalLevels;
        this.gridColumns = savedGame.gridColumns;
      }
    },
    saveGame() {
      let gameData = {
        gridSize: this.gridSize,
        tiles: this.tiles,
        gameStarted: this.gameStarted,
        paused: this.paused,
        matchedTiles: this.matchedTiles,
        score: this.score,
        currentLevel: this.currentLevel,
        totalLevels: this.totalLevels,
        gridColumns: this.gridColumns,
      };
      uni.setStorageSync('savedGame', gameData);
    },
    startGame() {
      this.gameStarted = true;
      this.paused = false;
      if (!this.loadGame()) {
        this.initBoard();
      }
    },
    pauseGame() {
      this.paused = true;
      this.saveGame();
    },
    resumeGame() {
      this.paused = false;
    },
    endGame() {
      this.gameStarted = false;
      this.paused = false;
      this.currentLevel = 1;
      this.gridSize = 16;
      this.gridColumns = 4;
      this.tiles.forEach(tile => (tile.isRevealed = false));
      uni.removeStorageSync('savedGame');
    },
    handleTileClick(index) {
      if (!this.gameStarted || this.paused) {
        return;
      }
      let tile = this.tiles[index];
      if (tile.isRevealed) {
        return;
      }

      this.$set(this.tiles, index, { ...tile, isRevealed: true });
      let revealedTiles = this.tiles.filter(t => t.isRevealed && !this.matchedTiles.includes(t.id));

      if (revealedTiles.length === 2) {
        if (revealedTiles[0].id === revealedTiles[1].id) {
          this.matchedTiles.push(revealedTiles[0].id);
          this.score += 10; // Add points for a match
          if (this.matchedTiles.length * 2 === this.gridSize) {
            this.score += 100; // Bonus score for completing a level
            if (this.currentLevel < this.totalLevels) {
              this.currentLevel++;
              this.gridSize += 4; // Increase grid size
              this.gridColumns = Math.sqrt(this.gridSize); // Adjust grid columns
              this.initBoard();
            } else {
              wx.showToast({
                title: 'You completed all levels!',
                icon: 'success',
                duration: 2000
              });
              this.endGame();
            }
          }
        } else {
          setTimeout(() => {
            this.tiles = this.tiles.map(t => ({
              ...t,
              isRevealed: this.matchedTiles.includes(t.id),
            }));
          }, 1000);
        }
      }
    },
    initBoard() {
      let tiles = [];
      for (let i = 0; i < this.gridSize; i++) {
        tiles.push({
          id: Math.floor(i / 2),
          content: `Color ${Math.floor(i / 2) }`, // More colors as levels increase
          isRevealed: false,
        });
      }
      this.tiles = this.shuffleArray(tiles);
    },
    shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.game-board {
  display: grid;
  grid-gap: 10px;
  margin-top: 20px;
}

.tile {
  width: 80px;
  height: 80px;
  position: relative;
}

.tile-inner {
  width: 100%;
  height: 100%;
  position: absolute;
  transition: transform 0.3s;
  transform-style: preserve-3d;
}

.revealed {
  transform: rotateY(180deg);
}

.tile-front,
.tile-back {
  width: 100%;
  height: 100%;
  position: absolute;
  backface-visibility: hidden;
}

.tile-front {
  background-color: #76448A;
}

.tile-back {
  background-color: #5DADE2;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotateY(180deg);
}

.start-button,
.end-button,
.pause-button,
.resume-button {
  margin: 20px;
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #1aad19;
  color: white;
  font-size: 16px;
  text-align: center;
}

.score-board, .level-board {
  margin-top: 10px;
  font-size: 16px;
  color: #333;
}
.	.games-box{
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
	}
	.u-button{
		width: auto;
		margin:20rpx;
	}
</style>
